import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { IResponse } from 'src/interfaces/response.interface';
import { User } from 'src/interfaces/user.interface';
import { UserService } from 'src/modules/user/user.service';
import { encript } from 'src/utils/encription';
import { JwtService } from '@nestjs/jwt';
const logger = new Logger('user.service');

@Injectable()
export class AuthService {
  private response: IResponse;
  constructor(
    @InjectModel('USER_MODEL') private readonly userModel: Model<User>,
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}
  /**
   * @description: 登录方法
   * @param {User} user
   * @return {Promise<IResponse>}
   */
  public async login(user: User): Promise<IResponse> {
    await this.validateUser(user)
      .then(async (res: IResponse) => {
        if (res.code != 200) {
          this.response = res;
          throw this.response;
        }
        this.response = {
          ...res,
          data: {
            token: await this.createToken(res.data),
            id: res.data.id,
          },
        };
        return this.response;
      })
      .catch((err) => {
        logger.log(err);
      });
    return this.response;
  }

  /**
   * @description: 注册方法
   * @param {User} user
   * @return {Promise<IResponse>}
   */
  public async regist(user: User): Promise<IResponse> {
    await this.userService
      .findOneByPhone(user.phone)
      .then((res) => {
        if (res.length > 0) {
          this.response = {
            code: 200,
            msg: `注册异常：已经存在用户${res[0]['phone']}`,
          };
          throw this.response;
        }
        return res;
      })
      .then(async () => {
        try {
          const createUser = new this.userModel(user);
          await createUser.save();
          this.response = {
            code: 200,
            msg: `注册成功。`,
          };
        } catch (error) {
          this.response = {
            code: 500,
            msg: `注册异常：无法保存用户信息到数据库。${error.message}`,
          };
          throw this.response;
        }
      })
      .catch((e) => {
        logger.log(e.msg);
        return e;
      });
    return this.response;
  }
  /**
   * @description: 验证用户信息是否正确
   * @param {User} user
   * @return {Promise<IResponse>}
   */
  private async validateUser(user: User): Promise<IResponse> {
    const phone: string = user.phone;
    const password: string = user.password;
    return await this.userService
      .findOneByPhone(phone)
      .then((res) => {
        if (res.length == 0) {
          this.response = { code: 201, msg: '用户尚未注册。' };
          throw this.response;
        }
        return res[0];
      })
      .then((dbUser: User) => {
        const pass = encript(password, dbUser.salt);
        if (pass == dbUser.password) {
          this.response = {
            code: 200,
            msg: '登录成功。',
            data: { id: dbUser._id, phone: dbUser.phone, roles: dbUser.roles },
          };
          return this.response;
        } else {
          this.response = { code: 201, msg: '用户名密码错误。' };
          throw this.response;
        }
      })
      .catch((err) => {
        return err;
      });
  }
  private createToken(user: User) {
    return this.jwtService.sign(user);
  }
  /**
   * @description: 修改用户信息
   * @Ahthor: xiaoxi
   * @param {User} user
   */
  public async modifyOneByPhone(user: User) {
    return await this.userService.findOneByPhone(user.phone).then(async () => {
      return await this.userModel
        .findOneAndUpdate({ phone: user.phone }, user, {}, () => {
          Logger.log('修改成功。');
        })
        .then(() => {
          return (this.response = { code: 200, msg: '修改成功。' });
        });
    });
  }
}
